# -*- coding: utf-8 -*-
# time: 2025/8/9 16:16
# file: models.py
# author: kai
# email: 1071664616@qq.com

"""
健康管理 models
"""
from django.db import models


class BodyRecord(models.Model):
    """
    身体指标记录
    """
    user_id = models.IntegerField(null=True, blank=True, verbose_name='用户')
    height = models.FloatField(null=True, blank=True, verbose_name='身高')
    weight = models.FloatField(null=True, blank=True, verbose_name='体重')
    low_pressure = models.FloatField(null=True, blank=True, verbose_name='低压')
    high_pressure = models.FloatField(null=True, blank=True, verbose_name='高压')
    blood_sugar = models.FloatField(null=True, blank=True, verbose_name='血糖')
    heart_rate = models.FloatField(null=True, blank=True, verbose_name='心率')
    record_date = models.DateTimeField(null=True, blank=True, verbose_name='记录日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'body_records'
        verbose_name = '身体指标记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user_id'], name='body_user_id_idx'),
            models.Index(fields=['created_at'], name='body_created_at'),
        ]

    def __str__(self):
        return f"BodyRecord {self.id}"
    
    @property
    def bmi(self):
        """计算BMI"""
        if self.height and self.weight and self.height > 0:
            height_in_meter = self.height / 100
            return round(self.weight / (height_in_meter * height_in_meter), 1)
        return None


class Post(models.Model):
    """
    帖子表
    """
    STATUS_CHOICES = [
        ('draft', '草稿，仅作者可见'),
        ('review', '审核中'),  # 新增审核中状态
        ('published', '已发布，所有人可见'),
        ('hidden', '已隐藏，仅管理员和作者可见'),
        ('deleted', '已删除，仅管理员可见（软删除）'),
        ('locked', '已锁定，禁止回复'),
        ('banned', '已封禁，内容不可见，仅管理员可见'),
    ]

    title = models.CharField(max_length=200, verbose_name="标题")
    content = models.TextField(verbose_name="内容")
    user_id = models.IntegerField(verbose_name='发布者ID')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='published', verbose_name="状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'health_post'
        verbose_name = '帖子'
        verbose_name_plural = '帖子'
        ordering = ['-created_at']

    def __str__(self):
        return self.title


class Comment(models.Model):
    """
    评论表
    """
    content = models.CharField(max_length=500, null=True, blank=True, verbose_name='内容')
    user_id = models.IntegerField(null=True, blank=True, verbose_name='评论人')
    pid = models.IntegerField(null=True, blank=True, verbose_name='父级ID')
    comment_time = models.CharField(max_length=255, null=True, blank=True, verbose_name='评论时间')
    fid = models.IntegerField(null=True, blank=True, verbose_name='关联ID')
    module = models.CharField(max_length=255, null=True, blank=True, verbose_name='模块')
    root_id = models.IntegerField(null=True, blank=True, verbose_name='根节点ID')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'comment'
        verbose_name = '评论表'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user_id'], name='comment_user_id'),
            models.Index(fields=['created_at'], name='comment_created_at'),
            models.Index(fields=['fid'], name='comment_fid'),
            models.Index(fields=['module'], name='comment_module'),
        ]

    def __str__(self):
        return f"Comment {self.id}"


class PostFavorite(models.Model):
    """
    帖子收藏表
    """
    user_id = models.IntegerField(verbose_name='用户ID')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='帖子')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='收藏时间')

    class Meta:
        db_table = 'post_favorites'
        verbose_name = '帖子收藏'
        verbose_name_plural = '帖子收藏'
        unique_together = ('user_id', 'post')  # 确保一个用户不能重复收藏同一个帖子

    def __str__(self):
        return f"User {self.user_id} favorite Post {self.post.id}"


class PostLike(models.Model):
    """
    帖子点赞/踩表
    """
    LIKE_CHOICES = [
        (1, '点赞'),
        (-1, '点踩'),
    ]

    user_id = models.IntegerField(verbose_name='用户ID')
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='帖子')
    like_type = models.IntegerField(choices=LIKE_CHOICES, verbose_name='点赞类型')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')

    class Meta:
        db_table = 'post_likes'
        verbose_name = '帖子点赞/踩'
        verbose_name_plural = '帖子点赞/踩'
        unique_together = ('user_id', 'post')  # 确保一个用户不能对同一个帖子既点赞又点踩

    def __str__(self):
        return f"User {self.user_id} {'like' if self.like_type == 1 else 'dislike'} Post {self.post.id}"


class EatingRecord(models.Model):
    """
    饮食记录
    """
    user_id = models.IntegerField(null=True, blank=True, verbose_name='用户')
    foods_name = models.CharField(max_length=255, null=True, blank=True, verbose_name='食物名称')
    intake = models.IntegerField(null=True, blank=True, verbose_name='摄入量')
    calorie = models.IntegerField(null=True, blank=True, verbose_name='卡路里')
    record_date = models.DateTimeField(null=True, blank=True, verbose_name='记录日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'eating_records'
        verbose_name = '饮食记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user_id'], name='eating_user_id'),
            models.Index(fields=['created_at'], name='eating_created_at'),
        ]

    def __str__(self):
        return f"EatingRecord {self.id}"

class Notice(models.Model):
    """
    系统公告
    """
    title = models.CharField(max_length=255, null=True, blank=True, verbose_name='标题')
    content = models.CharField(max_length=255, null=True, blank=True, verbose_name='内容')
    publish_time = models.CharField(max_length=255, null=True, blank=True, verbose_name='发布时间')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'notice'
        verbose_name = '系统公告'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"Notice {self.id}: {self.title}"

class SleepRecord(models.Model):
    """
    睡眠记录
    """
    user_id = models.IntegerField(null=True, blank=True, verbose_name='用户')
    sleep_time = models.CharField(max_length=255, null=True, blank=True, verbose_name='入睡时间')
    wakeup_time = models.CharField(max_length=255, null=True, blank=True, verbose_name='起床时间')
    sleep_duration = models.FloatField(null=True, blank=True, verbose_name='睡眠时长')
    sleep_quality = models.CharField(max_length=255, null=True, blank=True, verbose_name='睡眠质量')
    record_date = models.DateTimeField(null=True, blank=True, verbose_name='记录日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'sleep_records'
        verbose_name = '睡眠记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user_id'], name='sleep_user_id'),
            models.Index(fields=['created_at'], name='sleep_created_at'),
        ]

    def __str__(self):
        return f"SleepRecord {self.id}"


class SportsRecord(models.Model):
    """
    运动记录
    """
    user_id = models.IntegerField(null=True, blank=True, verbose_name='用户')
    type = models.CharField(max_length=255, null=True, blank=True, verbose_name='运动类型')
    during = models.IntegerField(null=True, blank=True, verbose_name='运动时长')
    distance = models.FloatField(null=True, blank=True, verbose_name='运动距离')
    calorie = models.FloatField(null=True, blank=True, verbose_name='卡路里')
    record_date = models.DateTimeField(null=True, blank=True, verbose_name='记录日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'sports_records'
        verbose_name = '运动记录'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user_id'], name='sports_user_id'),
            models.Index(fields=['created_at'], name='sports_created_at'),
        ]

    def __str__(self):
        return f"SportsRecord {self.id}"


class HealthNews(models.Model):
    """
    健康资讯表
    """

    title = models.CharField(max_length=255, verbose_name="文章标题")
    url = models.TextField(verbose_name="文章链接")
    publish_time = models.DateTimeField(verbose_name="发布时间")
    title_image = models.CharField(
        max_length=500, default="", verbose_name="标题图片链接"
    )
    hash_value = models.CharField(
        max_length=64, unique=True, verbose_name="文章唯一标识符"
    )
    website = models.CharField(max_length=100, verbose_name="来源网站")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = "health_news"
        verbose_name = "健康资讯文章"
        verbose_name_plural = "健康资讯文章"
        indexes = [models.Index(fields=["publish_time"], name="idx_publish_time")]

    def __str__(self):
        return self.title


class SensitiveWord(models.Model):
    LEVEL_BLOCK = 1
    LEVEL_REVIEW = 2
    LEVEL_REPLACE = 0

    LEVEL_CHOICES = [
        (LEVEL_REPLACE, "replace"),
        (LEVEL_BLOCK, "block"),
        (LEVEL_REVIEW, "review"),
    ]

    word = models.CharField(max_length=255, verbose_name="敏感词")
    category = models.CharField(max_length=100, verbose_name="敏感词分类")
    level = models.PositiveSmallIntegerField(
        choices=LEVEL_CHOICES,
        default=LEVEL_REPLACE,
        db_index=True,
        verbose_name="处理级别"
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = "sensitive_words"
        verbose_name = "敏感词"
        verbose_name_plural = "敏感词"
        unique_together = ["word", "category"]
        indexes = [
            models.Index(fields=["category"], name="idx_category"),
            models.Index(fields=["level"], name="idx_level"),
        ]

    def __str__(self):
        return f"{self.word} ({self.category})"

class ScheduledTask(models.Model):
    TASK_STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '停用'),
    ]

    TASK_TYPE_CHOICES = [
        ('news_crawler', '健康资讯爬虫'),
        ('words_crawler', '敏感词更新'),
        ('post_review', '帖子审核'),  # 添加帖子审核任务类型
        ('daily_health_analysis', '每日健康分析'),  # 添加每日健康分析任务类型
    ]

    name = models.CharField(max_length=100, verbose_name="任务名称")
    task_type = models.CharField(max_length=50, choices=TASK_TYPE_CHOICES, verbose_name="任务类型")
    cron_expression = models.CharField(max_length=100, verbose_name="Cron表达式")
    status = models.CharField(max_length=20, choices=TASK_STATUS_CHOICES, default='inactive', verbose_name="状态")
    last_run = models.DateTimeField(null=True, blank=True, verbose_name="上次执行时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        db_table = 'scheduled_tasks'
        verbose_name = '定时任务'
        verbose_name_plural = '定时任务'


class HealthReport(models.Model):
    """
    体检报告模型
    """
    STATUS_CHOICES = [
        ('uploaded', '已上传'),
        ('analyzing', '分析中'),
        ('completed', '分析完成'),
        ('failed', '分析失败'),
    ]
    
    user_id = models.IntegerField(verbose_name='用户ID')
    file_path = models.CharField(max_length=500, verbose_name='文件路径')
    uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    analysis_result = models.TextField(blank=True, null=True, verbose_name='分析结果')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='uploaded', verbose_name='分析状态')

    class Meta:
        db_table = 'health_reports'
        verbose_name = '体检报告'
        verbose_name_plural = '体检报告'
        indexes = [
            models.Index(fields=['user_id'], name='health_report_user_id_idx'),
            models.Index(fields=['uploaded_at'], name='health_report_uploaded_at_idx'),
        ]

    def __str__(self):
        return f"HealthReport {self.id} - User {self.user_id}"
    
    def get_status_display(self):
        """获取状态的中文显示"""
        status_map = dict(self.STATUS_CHOICES)
        return status_map.get(self.status, self.status)
